<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <link rel="stylesheet" href="dist/css/swiper-bundle.min.css">


</head>

<body>
    <div id="box">
        <!-- <swiper>
            <div class="swiper-slide">aaa</div>
            <div class="swiper-slide">bbb</div>
            <div class="swiper-slide">ccc</div>
        </swiper> -->

        <!-- 加key值的方案 -->
        <!-- <swiper :key="datalist.length">
            <div class="swiper-slide" v-for="data in datalist">
                {{data}}
            </div>
        </swiper> -->
        <!-- swiper第一次执行时
            swiper的key值为0；当ajax请求完毕数据后，
            此时新的
            swiper的key值为3，
            当key值不同时Vue内部算法diff会将key值进行对比将不一致时，旧的swiper会被销毁
            此时的swiper将会有数据-->

        <!-- 使用v-if的方案 -->
        <!-- 运行时v-if="datalist.length"长度为0不会有数据，请求结束后开始创建swiper，并开始向插槽中添加默认内容和指定内容
            同时传入myoptions{}属性进来
        -->
        <swiper v-if="datalist.length" :myoptions="{
            loop:true
        }">
            <div class="swiper-slide" v-for="data in datalist">
                {{data}}
            </div>

            <template #pagination>
                <div class="swiper-pagination"></div>
            </template>


        </swiper>

    </div>

    <script src="dist/js/swiper-bundle.min.js"></script>
    <script type="text/javascript">
        //全局定义swiper
        Vue.component("swiper", {
            props: ["myoptions"],
            template: `
            <div class="swiper-container kerwin">
            <div class="swiper-wrapper">
                <div class="swiper-slide">
                   <slot></slot>
                </div>
                    <slot name="pagination"></slot>  
            </div>
            <div class="swiper-pagination"></div>
        </div>
            `,

            mounted() {
                console.log("mounted", this.myoptions) //此处一运行
                var baseoptions = {
                    loop: false,
                    pagination: {
                        el: ".swiper-pagination",
                    },
                }
                new Swiper(".kerwin", object.assign(baseoptions, this.myoptions))
            },
            destroyed() {
                console.log("destroyed")
            },
        })

        var vm = new Vue({
            el: "#box",
            data: {
                datalist: [],
            },
            mounted() {
                setTimeout(() => {
                    this.datalist = ["aaa", "bbb", "ccc"]
                }, 2000)
            }
        })
    </script>
</body>

</html>